<template>
  <!-- 搜索栏 -->
  <el-card class="search-card">
    <el-form :model="searchForm" label-width="80px" inline>
      <el-form-item label="工单编号">
        <el-input v-model="searchForm.productionOrderCode" placeholder="工单编号" clearable />
      </el-form-item>
      <el-form-item label="工单名称">
        <el-input v-model="searchForm.productionOrderName" placeholder="工单名称" clearable />
      </el-form-item>
      <el-form-item label="单据来源">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderSource" placeholder="单据来源">
          <el-option label="客户订单" :value="1"/>
          <el-option label="库存备货" :value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input v-model="searchForm.material.code" placeholder="物料编号" clearable />
      </el-form-item>
      <el-form-item label="物料名称">
        <el-input v-model="searchForm.material.name" placeholder="物料名称" clearable />
      </el-form-item>

      <el-form-item label="客户编号">
        <el-input v-model="searchForm.customer.code" placeholder="客户编号" clearable />
      </el-form-item>
      <el-form-item label="客户名称">
        <el-input v-model="searchForm.customer.name" placeholder="客户名称" clearable />
      </el-form-item>
      <el-form-item label="工单类型">
        <el-select style="width: 120px" clearable v-model="searchForm.productionOrderType" placeholder="单据来源">
          <el-option
              v-for="dictData in productionOrderTypeDictDataList"
              :value="dictData.dictValue"
              :label="dictData.dictLabel"
              :key="dictData.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="需求日期">
        <el-date-picker
            v-model="searchForm.requestDate"
            type="date"
            placeholder="需求日期"
            :size="size"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 列表 -->
  <el-card class="table-card">
    <el-table
        :data="productionOrderList"
        border
        stripe
        @selection-change="handleSelectionChange"
    >
      <el-table-column prop="productionOrderCode" label="工单编号">
        <template #default="scope">
          <el-link type="primary">{{scope.row.productionOrderCode}}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="productionOrderName" label="工单名称"/>
      <el-table-column prop="typeDictData.dictLabel" label="工单类型"/>
      <el-table-column prop="productionOrderSource" label="工单来源">
        <template #default="scope">
          {{scope.row.productionOrderSource == 1?'客户订单':'库存备货'}}
        </template>
      </el-table-column>
      <el-table-column prop="orderCode" label="订单编号"/>
      <el-table-column prop="material.code" label="产品/物料编号"/>
      <el-table-column prop="material.name" label="产品/物料名称"/>
      <el-table-column prop="material.specification" label="规格"/>
      <el-table-column prop="material.unit.name" label="单位"/>
      <el-table-column prop="productionOrderQuantity" label="工单数量"/>
      <el-table-column label="已生产数量">
        {{0}}
      </el-table-column>
      <el-table-column prop="customer.code" label="客户编号"/>
      <el-table-column prop="customer.name" label="客户名称"/>
      <el-table-column prop="requestDate" label="需求日期"/>
      <el-table-column prop="statusDictData.dictLabel" label="状态"/>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleProschedule(scope.row)">排产</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
  <!-- 分页栏 -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>

  <!-- 排产弹窗 -->
  <el-dialog v-model="proscheduleDialogVisabel" title="生产排查" width="80%">
    <template #header>生产排查</template>
    <template #default>
        <el-form v-model="productionOrderForm">
          <el-form-item label="工单编号">
            <el-input v-model="productionOrderForm.productionOrderCode"/>
            <el-switch
                @click="autoCode"
                v-model="isAutoCode"
                size="large"
                inline-prompt
                active-text="生成"
                inactive-text="生成"/>
          </el-form-item>
          <el-form-item label="工单名称">
            <el-input v-model="productionOrderForm.productionOrderName"/>
          </el-form-item>
          <el-form-item label="来源类型">
            <el-radio-group v-model="productionOrderForm.productionOrderSource">
              <el-radio :label="1">客户订单</el-radio>
              <el-radio :label="2">库存备货</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 订单编号：仅当来源类型为客户订单（值为1）时显示 -->
          <el-form-item
              label="订单编号"
              prop="orderCode"
              v-if="productionOrderForm.productionOrderSource === 1">
            <el-input
                v-model="productionOrderForm.orderCode"
                placeholder="请输入订单编号"
                clearable/>
          </el-form-item>
          <el-form-item label="工单类型">
            <el-select v-model="productionOrderForm.productionOrderType" placeholder="请选择工单类型">
              <el-option label="自产" :value="1" />
              <el-option label="外协" :value="2" />
              <el-option label="外购" :value="3" />
            </el-select>
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="产品物料编码">
                <el-input v-model="productionOrderForm.materialCode" placeholder="产品物料编码">
                  <template #append>
                    <el-button @click="showMaterialList"><el-icon><Search /></el-icon></el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="产品物料名称">
                <el-input v-model="productionOrderForm.material.name" disabled placeholder="产品物料名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位">
                <el-input v-model="productionOrderForm.material.unit.name" disabled placeholder="单位"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="规格型号">
                <el-input type="textarea" v-model="productionOrderForm.material.specification" disabled placeholder=""/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="工单数量">
            <el-input v-model="productionOrderForm.productionOrderQuantity"/>
          </el-form-item>
          <el-form-item label="需求日期">
            <el-date-picker
                v-model="productionOrderForm.requestDate"
                type="date"
                placeholder="需求日期"
                :size="size"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="客户编码"
                            prop="customerCode"
                            v-if="productionOrderForm.productionOrderSource === 1">
                <el-input v-model="productionOrderForm.customerCode" placeholder="客户编码" clearable>
                  <template #append>
                    <el-button @click="showCustomerList"><el-icon><Search /></el-icon></el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="客户名称" v-if="productionOrderForm.productionOrderSource === 1">
                <el-input v-model="productionOrderForm.customer.name" disabled placeholder="客户名称"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      <div>
        <el-tabs type="border-card" @tab-click="handleWorkflowTabClick">
          <el-tab-pane
              v-for="workflow in workflowList"
              :name="workflow.id"
              :key="workflow.id"
              :label="workflow.workflowName">
            <el-tabs @tab-click="handleProcessTabClick">
              <el-tab-pane
                  v-for="process in workflow.processes"
                  :label="process.processName"
                  :name="process.id"
              >
                <el-card v-if="isEditProschedule">
                  <el-tabs type="border-card">
                    <el-tab-pane label="任务列表">
                      <ProscheduleTask :workflowId="currentWorkflowId"
                                       :processId="currentProcessId"
                                       :taskList="currentTaskList"
                      ></ProscheduleTask>
                    </el-tab-pane>
                  </el-tabs>
                </el-card>
              </el-tab-pane>
            </el-tabs>
          </el-tab-pane>
        </el-tabs>
      </div>
    </template>
    <template #footer>
      <el-button @click="proscheduleDialogVisabel = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import {ref, onMounted} from "vue";
import {ElMessage} from "element-plus";
//导入编写的production-order.js对应的API
import {getProductionOrderList, queryByCode} from "@/api/production-order.js";
import {getDictDataList} from "@/api/dictData.js";
//引入要用的API
import {getWorkflowByMaterialCode} from "@/api/workflow.js"
import {getProschedueTaskListByWorkflowId} from "@/api/proschedue_task.js"
import ProscheduleTask from "@/views/pro/proschedule/proschedule-task.vue";
//生产排产的弹窗
const proscheduleDialogVisabel = ref(false);
// 绑定搜索表单的数据
const searchForm = ref({
  productionOrderCode: "",
  productionOrderName: "",
  material: {code: "", name: ""},
  status: "",
  productionOrderSource: "",
  customer: {code: "", name: ""},
  productionOrderType: "",
  requestDate: ""
})
const productionOrderForm = ref({
  id:'',
  productionOrderCode:'',
  productionOrderName:'',
  productionOrderSource:'',
  productionOrderType:'',
  orderCode:'',
  materialCode:'',
  material:{unit:{}},
  productionOrderQuantity:'',
  customerCode:'',
  customer:{},
  requestDate:'',
  status: ''
})

// 商品的工艺列表
const workflowList = ref([]);
// 保存工单类型字典列表
const productionOrderTypeDictDataList = ref([]);
//保存查询的列表数据
const productionOrderList = ref([]);
// 分页相关数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
// 选中的工单
const selectedProschedule = ref([]);

// 处理选择改变
const handleSelectionChange = (selection) => {
  selectedProschedule.value = selection;
};

// 工具方法：规范化后端分页与列表返回
const toArray = (val) => Array.isArray(val) ? val : (val ? [val] : []);
const normalizeList = (res) => {
  // 常见结构:
  // 1) { code, data: { list, total } }
  // 2) { code, data: { records, total } }
  // 3) { data: [] } 或直接返回数组
  // 4) { list: [], total: n }
  const data = res?.data ?? res;
  let list = [];
  let total = 0;

  if (Array.isArray(data)) {
    list = data;
    total = data.length;
  } else if (Array.isArray(data?.list)) {
    list = data.list;
    total = Number(data?.total ?? list.length) || 0;
  } else if (Array.isArray(data?.records)) {
    list = data.records;
    total = Number(data?.total ?? data?.totalCount ?? list.length) || 0;
  } else if (Array.isArray(res?.list)) {
    list = res.list;
    total = Number(res?.total ?? list.length) || 0;
  } else if (Array.isArray(res?.records)) {
    list = res.records;
    total = Number(res?.total ?? res?.totalCount ?? list.length) || 0;
  }

  // 兜底：如果仍为空但 data 是对象且可迭代，尝试提取第一个数组字段
  if (list.length === 0 && data && typeof data === 'object') {
    for (const k of Object.keys(data)) {
      if (Array.isArray(data[k])) {
        list = data[k];
        break;
      }
    }
  }

  return { list, total };
};

// 改变了每页大小的事件
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize;
  handleSearch();
}

// 改变页面的事件 翻页事件
const handleCurrentChange = (newPage) => {
  pagination.value.currentPage = newPage;
  handleSearch();
}

// 状态字典
const statusDict = ref([]);
const getStatusDict = () => {
  return getDictDataList({dictType: "PRODUCTION_ORDER_STATUS"}).then(res => {
    const { list } = normalizeList(res);
    statusDict.value = list;
  }).catch(() => {
    statusDict.value = [];
  });
};

// 搜索数据的事件
const handleSearch = () => {
  // 从字典中找到“已审核”对应的状态值
  const targetStatus = statusDict.value.find(item => item.dictLabel === '已审核')?.dictValue;
  // 调用查询的接口查询数据
  let params = {
    productionOrderCode: searchForm.value.productionOrderCode,
    productionOrderName: searchForm.value.productionOrderName,
    materialCode: searchForm.value.material.code,
    materialName: searchForm.value.material.name,
    status: targetStatus, // 只显示已审核工单
    productionOrderSource: searchForm.value.productionOrderSource,
    customerCode: searchForm.value.customer.code,
    customerName: searchForm.value.customer.name,
    productionOrderType: searchForm.value.productionOrderType,
    requestDate: searchForm.value.requestDate,
    pageNum: pagination.value.currentPage,
    pageSize: pagination.value.pageSize
  };
  getProductionOrderList(params).then(res => {
    const { list, total } = normalizeList(res);
    productionOrderList.value = list;
    pagination.value.total = total;
    if (!Array.isArray(list)) {
      ElMessage.warning('列表数据格式异常，已采用兼容解析');
    }
  }).catch(err => {
    console.error('查询工单失败:', err);
    productionOrderList.value = [];
    pagination.value.total = 0;
    ElMessage.error('查询工单失败');
  })
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    productionOrderCode: "",
    productionOrderName: "",
    material: {code: "", name: ""},
    status: "",
    productionOrderSource: "",
    customer: {code: "", name: ""},
    productionOrderType: "",
    requestDate: ""
  };
  handleSearch();
}
// 加载工单类型字典的函数
const loadProductOrderDictDataList = () => {
  getDictDataList({dictType: "PRODUCTION_ORDER_TYPE"}).then(res => {
    const { list } = normalizeList(res);
    productionOrderTypeDictDataList.value = list;
  }).catch(() => {
    productionOrderTypeDictDataList.value = [];
  })
}
//当前选中的工艺编号
const currentWorkflowId = ref(undefined);
//定义进入生产排产的弹窗
const isEditProschedule = ref(false);
//生产排查的页面有原有数据回显和工艺以及对应的工序
const handleProschedule = (row)=>{
  isEditProschedule.value = true;
  //加载对应工单
  queryByCode(row.id).then(res=>{
    const data = res?.data || {};
    //先更新表单数据
    productionOrderForm.value = {
      ...data,
      customer: data.customer || {},
      material: data.material ? {
        ...data.material,unit: data.material.unit || {}
      } : {unit: {}}
    };
    //确保materialCode已更新后再加载工艺列表
    getWorkflowByMaterialCode(productionOrderForm.value.materialCode).then(res=>{
      const { list } = normalizeList(res);
      workflowList.value = list;
      //将第一个工艺id赋给currentWorkflowId并初始化工序
      if(workflowList.value.length > 0){
        currentWorkflowId.value = workflowList.value[0].id;
        // 初始化第一个工艺的第一个工序
        if(workflowList.value[0].processes && workflowList.value[0].processes.length > 0){
          currentProcessId.value = workflowList.value[0].processes[0].id;
          // 加载该工序的任务列表
          loadTaskListByProcessId(currentProcessId.value);
        }
      }
    }).catch(err => {
      console.error('加载工艺列表失败:', err);
      workflowList.value = [];
    })
  })
  //弹出窗体
  proscheduleDialogVisabel.value = true;
}
//记录选中的工艺流程
const handleWorkflowTabClick = (panel)=>{
  currentWorkflowId.value = panel.props.name;
  // 切换工艺时自动选中第一个工序
  const currentWorkflow = workflowList.value.find(workflow => workflow.id === currentWorkflowId.value);
  if(currentWorkflow && currentWorkflow.processes && currentWorkflow.processes.length > 0){
    currentProcessId.value = currentWorkflow.processes[0].id;
    loadTaskListByProcessId(currentProcessId.value);
  }
}
//当前选中的工序编号
const currentProcessId = ref(undefined);
//工序的tab选中触发的事件
const handleProcessTabClick = (panel)=>{
  //保存当前点击的工序ID
  const targetProcessId = panel.props.name;
  console.log('点击工序:', { 
    panel: panel, 
    targetProcessId: targetProcessId, 
    type: typeof targetProcessId 
  });
  
  currentProcessId.value = targetProcessId;
  loadTaskListByProcessId(targetProcessId);
}
const currentTaskList = ref([]);
//查询任务列表
const loadTaskListByProcessId=(targetProcessId)=>{
  const currentWorkflowIdVal = currentWorkflowId.value;
  console.log('加载任务列表:', { workflowId: currentWorkflowIdVal, processId: targetProcessId, type: typeof targetProcessId });
  
  // 确保targetProcessId是数字类型
  const processIdNum = Number(targetProcessId);
  
  // 调用API加载指定工艺和工序的任务列表
  getProschedueTaskListByWorkflowId(currentWorkflowIdVal).then(res => {
    console.log('API返回结果:', res);

    const { list } = normalizeList(res);
    const sourceList = Array.isArray(list) ? list : [];
    console.log('原始任务列表(兼容后):', sourceList);

    // 过滤当前工序的任务列表，使用严格的数据类型比较
    const filteredTasks = sourceList.filter(task => {
      const taskProcessId = Number(task?.processId);
      const isMatch = taskProcessId === processIdNum;
      console.log('检查任务:', {
        taskId: task?.id,
        taskProcessId: task?.processId,
        taskProcessIdNum: taskProcessId,
        targetProcessId: targetProcessId,
        targetProcessIdNum: processIdNum,
        isMatch: isMatch
      });
      return isMatch;
    });

    console.log('过滤后的任务列表:', filteredTasks);
    currentTaskList.value = filteredTasks;

    if (filteredTasks.length === 0) {
      console.warn('当前工序没有任务数据，工序ID:', processIdNum);
    }
  }).catch(error => {
    console.error('加载任务列表失败:', error);
    currentTaskList.value = [];
  })
}
onMounted(async () => {
  loadProductOrderDictDataList();
  // 先等待字典加载完成，再执行搜索
  await getStatusDict();
  handleSearch();
});
</script>

<style scoped>
.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
}
</style>